package gui.commands.classDiagramCommands;

import data.DataVector;
import data.classDiagram.Entity;
import data.classDiagram.Method;
import data.classDiagram.MethodArgument;
import gui.commands.ICommand;

/**
 * User: Szymon Kudzia
 * Date: 10.05.13
 * Time: 15:10
 */
public class AddNewMethodCommand implements ICommand {
	protected Entity entity;
	protected Method method;

	protected String name;
	protected String unknown;
	protected String type;
	protected boolean isStatic;
	protected String visibility;
	protected String[] arguments;

	public AddNewMethodCommand(String name, String unknown, String type, boolean isStatic, String visibility, String[] arguments) {
		this.name = name;
		this.unknown = unknown;
		this.type = type;
		this.isStatic = isStatic;
		this.visibility = visibility;
		this.arguments = arguments;
	}

	@Override
	public void execute() {
		method = new Method();
		method.setName(name);
		method.setReturnType(type != null ? type : unknown);
		method.setStatic(isStatic);

		getMethodArguments(arguments);

		entity = DataVector.getInstance().getActiveEntity();
		DataVector.getInstance().addMethodToActiveEntity(method);
	}

	@Override
	public void undo() {
		entity.getMethods().remove(method);
		DataVector.getInstance().refresh();
	}

	@Override
	public void redo() {
		entity.addMethod(method);
		DataVector.getInstance().refresh();
	}


	protected void getMethodArguments(String[] arguments)
	{
		for (String arg : arguments){
			MethodArgument ma = getMethodArgument(arg);

			if (ma != null)
				method.addArgument(ma);
		}
	}

	protected MethodArgument getMethodArgument(String arg)
	{
		String[] argArray = arg.split(":");

		if (argArray.length < 1){
			System.out.println("Invalid argument definition");
			return  null;
		}

		MethodArgument methodArgument = new MethodArgument();
		String argName = argArray[0];
		String argType;
		String argDefaultValue;

		if (argArray[1].contains("=")){
			String[] argArray2 = argArray[1].split("=");
			argType = argArray2[0];
			argDefaultValue = argArray2[1];
			methodArgument.setDefaultValue(argDefaultValue);
		} else {
			argType = argArray[1];
		}

		methodArgument.setName(argName);
		methodArgument.setType(argType);

		return methodArgument;
	}
}
